import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import analyticsApi from '../api/analytics'; // We will create this file next

export function useAnalyticsData() {
    // State
    const timeRange = ref([]);
    const currentTime = ref('');
    const insightsLoading = ref(false);
    const trendType = ref('users');
    
    // Data containers
    const realtimeStats = ref([]);
    const heatmapData = ref([]);
    const aiInsights = ref([]);
    const trendData = reactive({
        users: { labels: [], data: [], forecast: [] },
        activities: { labels: [], data: [], forecast: [] },
        revenue: { labels: [], data: [], forecast: [] },
    });
    const behaviorMetrics = ref([]);
    const anomalies = ref([]);

    let timer;

    // Fetch all dashboard data
    const fetchDashboardData = async () => {
        insightsLoading.value = true;
        try {
            const [
                statsRes,
                heatmapRes,
                insightsRes,
                trendsRes,
                behaviorRes,
                anomaliesRes
            ] = await Promise.all([
                analyticsApi.getRealtimeStats(),
                analyticsApi.getHeatmapData(),
                analyticsApi.getAiInsights(),
                analyticsApi.getTrendData(),
                analyticsApi.getBehaviorMetrics(),
                analyticsApi.getAnomalies()
            ]);

            realtimeStats.value = statsRes.data;
            heatmapData.value = heatmapRes.data;
            aiInsights.value = insightsRes.data;
            Object.assign(trendData, trendsRes.data);
            behaviorMetrics.value = behaviorRes.data;
            anomalies.value = anomaliesRes.data;

        } catch (error) {
            ElMessage.error('获取分析数据失败');
            console.error("Failed to fetch dashboard data:", error);
        } finally {
            insightsLoading.value = false;
        }
    };
    
    // Methods
    const handleTimeChange = (newRange) => {
        console.log('Time range changed:', newRange);
        // Here you would typically refetch data with the new time range
        // fetchDashboardData({ from: newRange[0], to: newRange[1] });
        ElMessage.info('日期范围已更改，正在重新加载数据...');
        fetchDashboardData();
    };
    
    const refreshInsights = async () => {
        insightsLoading.value = true;
        try {
            const res = await analyticsApi.getAiInsights();
            aiInsights.value = res.data;
            ElMessage.success('AI洞察已刷新');
        } catch (error) {
            ElMessage.error('刷新AI洞察失败');
        } finally {
            insightsLoading.value = false;
        }
    };
    
    const updateCurrentTime = () => {
        const now = new Date();
        currentTime.value = now.toLocaleTimeString('zh-CN');
    };

    onMounted(() => {
        fetchDashboardData();
        updateCurrentTime();
        timer = setInterval(updateCurrentTime, 1000);
    });

    onUnmounted(() => {
        if (timer) {
            clearInterval(timer);
        }
    });

    return {
        timeRange,
        currentTime,
        insightsLoading,
        trendType,
        realtimeStats,
        heatmapData,
        aiInsights,
        trendData,
        behaviorMetrics,
        anomalies,
        fetchDashboardData,
        handleTimeChange,
        refreshInsights,
    };
} 